package com.atguigu.redis7.service;

import com.atguigu.redis7.entities.Customer;
import com.atguigu.redis7.mapper.CustomerMapper;
import com.atguigu.redis7.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @版本： V5.1.0
 * @版权： Copyright @ 2025 广东广昱信息科技有限公司版权所有
 * @作者： 广东广昱信息科技有限公司
 * @日期： 2025-07-13 16:55
 */
@Slf4j
@Service
public class CustomerService {
    public static final String CACHA_KEY_CUSTOMER = "customer:";

    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CheckUtils checkUtils;

    /**
     * 写操作
     * @param customer
     */
    public void addCustomer(Customer customer){
        int i = customerMapper.insertSelective(customer);
        if(i>0){
            //mysql插入成功，需要重新查询一次将数据捞出来，写进redis
            Customer result = customerMapper.selectByPrimaryKey(customer.getId());
            //redis缓存key
            String key =CACHA_KEY_CUSTOMER+customer.getId();
            //捞出来的数据写进redis
            redisTemplate.opsForValue().set(key,result);
        }
    }

    public Customer findCustomerById(Integer customerId){
        Customer customer = null;
        //缓存redis的key名称
        String key = CACHA_KEY_CUSTOMER+customerId;
         customer = (Customer) redisTemplate.opsForValue().get(key);
        //2.redis有直接返回，没有再去查询mysql
        if(customer==null){
            //3.再去查询我们的mysql
            customer = customerMapper.selectByPrimaryKey(customerId);
            //3.1mysql有,redis无
            if(customer!=null){
                //3.2把mysql查出来的数据回写到redis,保持一致性
                redisTemplate.opsForValue().set(key,customer);
            }
        }
        return customer;
    }

    public Customer findCustomerByIdWithBloomFilter(Integer customerId){
        Customer customer = null;
        //缓存redis的key名称
        String key = CACHA_KEY_CUSTOMER+customerId;
        //布隆过滤器chek,无是绝对无，有是可能有
        if(!checkUtils.checkWithBloomFilter("whitelistCustomer", key)){
            log.info("白名单无此顾客，不可访问"+key);
            return null;
        }

        //==============================
        customer = (Customer) redisTemplate.opsForValue().get(key);
        //2.redis有直接返回，没有再去查询mysql
        if(customer==null){
            //3.再去查询我们的mysql
            customer = customerMapper.selectByPrimaryKey(customerId);
            //3.1mysql有,redis无
            if(customer!=null){
                //3.2把mysql查出来的数据回写到redis,保持一致性
                redisTemplate.opsForValue().set(key,customer);
            }
        }
        return customer;
    }
}
